var DEBUG = false;
String.prototype.endWith = function (a) {
	if (a == null || a == "" || this == null || this.length == 0 || a.length > this.length) {
		return false
	}
	if (this.substring(this.length - a.length).toLowerCase() == a.toLowerCase()) {
		return true
	} else {
		return false
	}
	return true
};
var ImageType = {
	IMG: "IMG",
	TEXT: "TEXT",
	LINK: "LINK",
	INPUT_IMG: "INPUT_IMG"
};
var chromeSender = chrome.extension.sendMessage;
if (typeof chromeSender != "function") {
	chromeSender = chrome.extension.sendRequest
}
var ImageManager = function () {};
ImageManager.prototype = {
	imgList: [],
	getImage: function (config) {
		console.log("ImageManager.getImage");
		this.imgList = [];
		this.config = eval(config);
		var imgs = document.getElementsByTagName("img");
		for (var i = 0; i < imgs.length; i++) {
			var img = imgs[i];
			var newImg = new Image();
			newImg.src = img.src;
			var width = 0,
				height = 0;
			width = parseInt(img.naturalWidth);
			height = parseInt(img.naturalHeight);
			nwidth = parseInt(newImg.width);
			nheight = parseInt(newImg.height);
			width = nwidth > width ? nwidth : width;
			height = nheight > height ? nheight : height;
			newImg = null;
			this.addImg(ImageType.IMG, img.src, width, height)
		}
		var inputs = document.getElementsByTagName("input");
		for (var i = 0; i < inputs.length; i++) {
			var input = inputs[i];
			var type = input.type;
			if (type.toUpperCase() == "IMAGE") {
				var src = input.src;
				this.addImg(ImageType.INPUT_IMG, src, 0, 0)
			}
		}
		var links = document.getElementsByTagName("a");
		for (var i = 0; i < links.length; i++) {
			var link = links[i];
			var href = link.href;
			if (href.endWith(".jpg") || href.endWith(".jpeg") || href.endWith(".bmp") || href.endWith(".ico") || href.endWith(".gif") || href.endWith(".png")) {
				this.addImg(ImageType.LINK, href, 0, 0)
			}
		}
		chromeSender({
			cmd: "ADD_PIC",
			outputTabId: this.config.outputTabId,
			imgList: this.imgList
		});
		return this.imgList
	},
	addImg: function (d, f, c, a) {
		var e = this;
		var b = this.getBigImgUrl(f);
		if (b != f) {
			f = b;
			c = 0;
			a = 0
		}
		this.imgList.push({
			type: d,
			src: f,
			width: c,
			height: a
		})
	},
	getBigImgUrl: function (src) {
		var rules = this.config.rules;
		console.log("src:", src);
		for (var i = 0; i < rules.length; i++) {
			var rule = rules[i];
			var srcPattern = new RegExp(rule.srcPattern);
			var replaceRule = rule.replaceRule;
			if (srcPattern && srcPattern.test(src)) {
				var ret = src;
				try {
					ret = eval(replaceRule.replace(/@/g, src));
					if (DEBUG) {
						console.log("ret:", ret)
					}
					return ret
				} catch (e) {
					console.log("image rule error:", e)
				}
			}
		}
		return src
	}
};
var imageManager = new ImageManager();